package top.zsyle.basic.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import top.zsyle.basic.annotation.PreAuthorize;
import top.zsyle.basic.jwt.JwtUtils;
import top.zsyle.basic.jwt.Payload;
import top.zsyle.basic.jwt.RsaUtils;
import top.zsyle.basic.jwt.UserInfo;
import top.zsyle.basic.util.ThreadLocalUtil;
import top.zsyle.system.mapper.PermissionMapper;
import top.zsyle.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    // 使用SPEL表达式获取到yml中的自定义配置，也就是私钥的文件名称
    @Value("${jwt.rsa.pub}")
    private String jwtRsaPub;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("444444444444");
        //1.获取header中的taken 判断其是否为空
        String token = request.getHeader("token");
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        if (StringUtils.isNotBlank(token)){
            //不是空
//            Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(token);
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPub).getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            //登录信息是否存在
            if (null != payload.getUserInfo()) {
                // 如果用户信息不为空，我们继续判断用户是否拥有访问此URL的权限
                // 将Object类型的logininfo拷贝到Logininfo对象中
                // 判断是否是员工
                // 如果是后台 我们才判断是否有权限
                Logininfo logininfo = payload.getUserInfo().getLogininfo();
                //todo 添加ThreadLocal
                ThreadLocalUtil.setUserInfo(payload.getUserInfo());
                if ( 0 == logininfo.getType()) {
                    // 进入到此判断说明是员工，那么获取到用户访问接口我们自定义的@PreAuthorize注解的sn值，用来确定用户访问的是那个URL权限
                    // 得到本次请求的方法对象
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    // 从方法对象中的到指定注解
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    // 判断方法上是否有此注解，如果没有说明是公共资源
                    if(preAuthorize != null){
                        // 从注解中获取到sn值，也就是本次请求对应的权限编码，用于判断用户是否有此URL权限
                        String permissionSn = preAuthorize.sn();
                        // 获取到用户所拥有的所有权限
//                        List<String> ownPermissions = permissionMapper.findAllByLogininfoId(logininfo.getId());
                        List<String> ownPermissions = payload.getUserInfo().getPermissions();
                        if (!ownPermissions.contains(permissionSn)) {
                            // 员工所有的权限不包含访问的权限，那么直接设置响应信息并拦截
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
                //重置token的过期时间
//                redisTemplate.expire(token,30,TimeUnit.MINUTES);
                return true;
            }
        }
        //2.返回resultObj为“nologin”

        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;
    }
}
